<template>
  <div>
    <!-- 筛选条件 -->
    <div class="filter">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.value }"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }} <span v-if="tab.count !== null">{{ tab.count }}</span>
      </button>
    </div>

    <!-- 作业列表 -->
    <div
      v-for="assignment in paginatedAssignments"
      :key="assignment.homework_id"
      class="assignment-card"
      @click="navigateToAssignmentDetail(assignment.homework_id)"
    >
      <div v-if="assignment.is_submit" class="completed-watermark">
        <img src="@/assets/picture/isSubmit.png" alt="已完成" />
      </div>
      <div class="assignment-content">
        <div class="assignment-header">
          <span class="badge" :class="statusBadgeClass(assignment.hmk_status)">
            {{ statusLabel(assignment.hmk_status) }}
          </span>
          <p style="font-weight:bold;">{{ assignment.hmk_title }}</p>
        </div>
        <p>{{ assignment.hmk_content }}</p>
        <div style="display:flex; font-size: 12px; color: gray;">
          <p style="margin-right: 10px; margin-left: 75px;">开始时间: {{ assignment.start_time }}</p>
          <p style="margin-right: 10px;">结束时间:{{ assignment.end_time }}</p>
          <p style="margin-right: 10px;" v-if="assignment.is_remit">补交截止时间: {{ assignment.remit_time }}</p>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <PagiNation :currentPage="currentPage" :totalPages="totalPages" @page-change="handlePageChange" />
  </div>
</template>


<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';  // 引入 useRouter
import { StufetchAssignments} from '@/services/api';
import PagiNation from '@/components/PagiNation.vue';

export default {
  name: 'StuAssignments',
  components: {
    PagiNation,
  },
  props: {
    classId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const currentTab = ref('全部作业');
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const tabs = ref([
      { label: '全部作业', value: '全部作业', count: null },
      { label: '进行中', value: 1, count: null },
      { label: '补交中', value: 2, count: null }, 
      {label: '互评中', value: 3, count: null },
      { label: '已截止', value: 4, count: null },
      
    ]);

    const router = useRouter(); // 使用 useRouter

    const navigateToAssignmentDetail = (homeworkId) => {
      const selectedAssignment = assignments.value.find((assignment) => assignment.homework_id === homeworkId);
      if (selectedAssignment) {
      // 存储作业标题和状态到 localStorage
      localStorage.setItem('hmk_title', selectedAssignment.hmk_title);
      localStorage.setItem('hmk_status', selectedAssignment.hmk_status);
      localStorage.setItem('is_submit', selectedAssignment.is_submit);
    }

      // 传递 semesterId
      router.push({ name: 'StuAssignmentList', params: { homeworkId, semesterId: props.classId } });
    };

    const assignments = ref([]);

    const loadAssignments = async () => {
      try {
        const userId = localStorage.getItem('id');
        const response = await StufetchAssignments(props.classId, userId);
        if (response.data.status === 1) {
          assignments.value = response.data.data.map((assignment) => ({
            ...assignment,
          }));

          // 修正 tab 统计
          tabs.value.forEach((tab) => {
            if (tab.value === '全部作业') {
              tab.count = assignments.value.length;
            } else {
              tab.count = assignments.value.filter((assignment) => assignment.hmk_status === tab.value).length;
            }
          });
        } else {
          console.error('获取作业列表失败，错误信息:', response.data.msg);
        }
      } catch (error) {
        console.error('加载作业失败:', error);
      }
    };

    const filteredAssignments = computed(() => {
      if (currentTab.value === '全部作业') {
        return assignments.value;
      } else {
        return assignments.value.filter((assignment) => assignment.hmk_status === currentTab.value);
      }
    });

    const paginatedAssignments = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredAssignments.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredAssignments.value.length / itemsPerPage);
    });

    const changeTab = (tabValue) => {
      currentTab.value = tabValue;
      currentPage.value = 1;
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    const statusLabel = (status) => {
      switch (status) {
        case 1:
          return '进行中';
        case 2:
          return '补交中';
        case 3:
          return '互评中';
        case 4:
          return '已截止';
      }
    };

    const statusBadgeClass = (status) => {
      switch (status) {
        case 1:
          return 'badge-unstart';
        case 2:
          return 'badge-in-progress';
        case 3:
          return 'badge-new';
        case 4:
          return 'badge-closed';
      }
    };

    onMounted(() => {
      loadAssignments();
    });

    return {
      currentTab,
      tabs,
      currentPage,
      totalPages,
      assignments,
      filteredAssignments,
      paginatedAssignments,
      statusLabel,
      statusBadgeClass,
      changeTab,
      handlePageChange,
      navigateToAssignmentDetail,
    };
  },
};
</script>

<style scoped>

.editor-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-button,
.submit-button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.cancel-button {
  background-color: #f0f0f0;
  color: #333;
}

.submit-button {
  background-color: #244382;
  color: #fff;
}

.submit-button:hover {
  background-color: #1e3661;
}

.filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter button {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

.filter button.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}

.filter .create-button {
  margin-left: auto;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter .create-button:hover {
  background-color: #376edc;
}

.assignment-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s;
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.assignment-card:hover {
  transform: translateY(-5px);
  background-color: #f0f0f0;
}
.assignment-header {
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}

.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}

.badge-unpublished {
  background-color: #ffd6d6;
  color: #d9534f;
}
.badge-unstart{
  background-color: #cae2f9;
  color: #519bd5;
}

.badge-in-progress {
  background-color: #d6ffdb;
  color: #3b995c;
}

.badge-closed {
  background-color: #f0f0f0cc;
  color: #666;
}
.badge-new{
    background-color: #f3e4b7f0;
  color:  #dda90ff0;
}

.assignment-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
  position: absolute;
  right: 0;
  top: 0;
}
.assignment-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s;
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

/* 已完成水印 */
.completed-watermark {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}

.completed-watermark img {
  width: 50px;  /* 设置水印图片的大小 */
  height: auto;
}
</style>
